


import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../api/DictApi.dart';
import '../../../utils/Settings.dart';
import '../../../utils/StoreData.dart';
import '../../../utils/Utils.dart';
import '../../form/LFormLogic.dart';
import '../../get/MyController.dart';
import 'LFormTreeState.dart';
import 'TreeMultiSelect.dart';
import 'TreeSingleSelect.dart';


class LFormTreeLogic extends MyController{

  final state = LFormTreeState();
  late List defaultValList;

  void init({required Map formItem,required Map formData,String? betweenSign,required String formTag,required String formType}){
    state.formItem = formItem;
    state.formData = formData??{};
    state.defaultText = "";
    state.betweenSign = betweenSign??"";
    state.resultOptions = [];
    state.dictOptions = [];
    state.selectedOption = {};//选中的
    state.formTag = formTag;
    state.formType = formType;
    state.checkVals = {};
    state.checkTexts = {};

    initDic();
  }

  void initDic()async{
    if(state.formItem["dictCode"]==null){
      return;
    }
    //初始化数据字典信息
    await DictApi.initDict(state.formItem["dictCode"], "", []);
    state.resultOptions = StoreData.dictInfo[state.formItem["dictCode"]];
    state.dictOptions = state.resultOptions;

    ///如果有默认值
    if(!Utils.isEmpty(state.formData['${state.formItem["field"]}${state.betweenSign}'])){
      defaultValList = state.formData['${state.formItem["field"]}${state.betweenSign}'].toString().split(",");
    }

    initDefault(state.dictOptions);

    ///如果是多选，将最后一个,去掉
    if(!Utils.isEmpty(state.defaultText)){
      state.defaultText = state.defaultText.substring(0, state.defaultText.lastIndexOf(','));//将字符串最后面字符去掉 all为数组
    }
    update();
  }


  initDefault(options){
    for(int i=0;i<options.length;i++ ){
      state.checkTexts[options[i]["value"]]= options[i]["title"];
      state.checkVals[options[i]["value"]] = false;
      if(defaultValList.isNotEmpty){
        if(defaultValList.contains(options[i]["value"])){
          state.defaultText += "${options[i]["title"]},";
          state.checkVals[options[i]["value"]] = true;
        }
      }
      if(options[i]["children"]!=null){
        initDefault(options[i]["children"]);
      }
    }

    update();
  }

  void onSelected(item){
    if(state.formData['${state.formItem["field"]}${state.betweenSign}'] != item["value"]){
      state.formData['${state.formItem["field"]}${state.betweenSign}'] = item["value"];
      state.defaultText = item["title"];
      if(state.formType==Settings.formType["表单"]){
        Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':item["value"]});
      }
      update();
    }
  }

  void onMultiSelected(){
    state.formData['${state.formItem["field"]}${state.betweenSign}'] = "";
    state.defaultText = "";
    state.checkVals.forEach((key, value) {
      if(value==true){
        state.defaultText += "${state.checkTexts[key]},";
        state.formData['${state.formItem["field"]}${state.betweenSign}'] += "$key,";
      }
    });

    if(!Utils.isEmpty(state.defaultText)){
      state.defaultText = state.defaultText.substring(0, state.defaultText.lastIndexOf(','));//将字符串最后面字符去掉 all为数组
      state.formData['${state.formItem["field"]}${state.betweenSign}'] = state.formData['${state.formItem["field"]}${state.betweenSign}'].substring(0, state.formData['${state.formItem["field"]}${state.betweenSign}'].lastIndexOf(','));
    }else{
      state.formData['${state.formItem["field"]}${state.betweenSign}'] = null;
    }
    if(state.formType==Settings.formType["表单"]){
      Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':state.formData['${state.formItem["field"]}${state.betweenSign}']});
    }
    update();
  }

  //清空选择
  void onClear(){
    state.checkVals.forEach((key, value) {
      state.checkVals[key] = false;
    });
    //清空选择的内容
    if(state.formData['${state.formItem["field"]}${state.betweenSign}'] != null){
      state.formData['${state.formItem["field"]}${state.betweenSign}'] = null;
      state.defaultText = "";
      if(state.formType==Settings.formType["表单"]){
        Get.find<LFormLogic>(tag: state.formTag).onChange({'field':'${state.formItem["field"]}${state.betweenSign}','val':null});
      }
      update();
    }

  }


  Future<dynamic> showCustomModalBottomSheet(context, List options) async {

    return showModalBottomSheet<dynamic>(
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      context: context,
      builder: (BuildContext context) {
        return Container(
          clipBehavior: Clip.antiAlias,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.0),
              topRight: Radius.circular(20.0),
            ),
          ),
          height: MediaQuery.of(context).size.height / 2.0,
          child: Column(
              children: [
            SizedBox(
              height: 50,
              child: Stack(
                textDirection: TextDirection.rtl,
                children: [
                  Align(
                    alignment: Alignment.topLeft,
                    child: IconButton(
                        icon: const Icon(Icons.arrow_back_ios),
                        onPressed: () async{
                          Get.back();
                          onClear();
                        }),
                  ),
                  Center(
                    child: Text(
                      '${state.formItem["label"]}选择',
                      style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0),
                    ),
                  ),
                  state.formItem["isCheckbox"]==true?TextButton(
                    onPressed:(){
                      Get.back();
                      onMultiSelected();
                    } ,
                    child: const Text('确定',style: TextStyle(fontSize: 16,)),
                  ):IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: () {
                      Get.back();
                    }
                  ),


                ],
              ),
            ),
            const Divider(height: 1.0),
            Expanded(
              child: state.formItem["isCheckbox"]==true?TreeMultiSelect(options: state.dictOptions,checkVals:state.checkVals,tag: '${state.formTag}#${state.formItem['field']}',):TreeSingleSelect(state: state,tag: '${state.formTag}#${state.formItem['field']}',)
            ),
          ]),
        );
      },
    );
  }
}